import axios from 'axios'
import store from '../store'
import router from '../router'
import ElementUI from 'element-ui'

const Axios = axios.create({
    baseURL: process.env.NODE_ENV === "development" ? '/dingxiang' : 'http://www.shuiyue.info:21000',
    timeout: 5000
})

/** 请求拦截器 */
Axios.interceptors.request.use(function(config) {
    const _urls = [
        '/user/login',
        '/auto/login',
        '/qrcode/code',
        '/qrcode/loop'
    ]

    if (_urls.includes(config.url)) {
        return config
    }

    let token = store.getters['common/token']
    console.log(token);
    if (!token) {
        return Promise.reject({code: 9000, message: '请求已被拦截，没有登录'})
    }

    config.headers['X-Token'] = token
    return config
})

/**
 * 封装的请求
 * @param {{url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', data: any, params: any}} req 
 * @returns 
 */
 export default req => {
    return new Promise(resolve => {
        Axios.request({
            url: req.url,
            method: req.method || 'get',
            data: req.data || {},
            params: req.params || {}
        }).then(({ data }) => {
            resolve(data)
            if(data.code !== 200 && data.message === 'token票据已过期，请重新登录'){
                
                router.push({
                    name:'login',
                    params:{
                        msg:data.message
                    }
                })
            }
        }).catch(e => {
            resolve(e)
        })
    })
}